<?php

namespace app\applet\controller\work_area;

use app\admin\service\work_area\BusinessService;
use app\common\controller\Applet;
use app\common\model\haikang\HkConsumerMsg;
use app\common\model\haikang\HkConsumerMsgWeek;
use app\common\model\haikang\HkEventType;
use app\common\model\work_area\HkDeviceSerial;
use app\common\model\work_area\WorkArea;
use app\common\model\work_area\WorkAreaStand;
use app\common\service\haikang\HaikangService;
use hg\apidoc\annotation as Apidoc;
use thans\jwt\facade\JWTAuth;

/**
 * @Apidoc\Title("所有数据")
 */
class Info extends Applet
{

    //中间件不验证的方法
    protected $middleware = [
        'app\\middleware\\Applet' => [
            'except' => ['projContrast', 'consumerMsgListExport', 'warningStatistics', 'earlyWarning']
        ]
    ];

    /**
     * @Apidoc\Title("事件列表")
     * @Apidoc\Url("/applet/work_area.Info/eventTypeList")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="事件名"),
     * )
     */
    public function eventTypeList()
    {
        //只获取下面数组事件
        $event_arr_id = HkEventType::$event_arr_id;
        $hk_event_type = HkEventType::where(['id' => $event_arr_id])->field('id,remarks')->select()->toArray();
        return $this->ajax(1, "成功", $hk_event_type);
    }


    /**
     * @Apidoc\Title("指挥部事件总统计")
     * @Apidoc\Url("/applet/work_area.Info/homeInfo")
     * @Apidoc\Param("date_type",type="int", desc="1今日 2昨日 3历史")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="工点id 默认值传0")
     * @Apidoc\Param("keyword_time",type="array", desc="工时间筛选")
     * @Apidoc\Param("event_arr_id",type="array", desc="事件类型id数组")
     * @Apidoc\Param("channel_no",type="string", desc="通道号")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     *    @Apidoc\Returned("count", type="int", desc="次数"),
     * )
     */
    public function homeInfo()
    {
        try {
            $device_serial_where = [];
            $date_type = input('post.date_type/d', 3);
            $work_area_id = input('post.work_area_id/d', 0);
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            $channel_no = input('post.channel_no/s', '');
            $event_arr_id = input('post.event_arr_id/a', HkEventType::$event_arr_id);
            $event_arr_id = empty($event_arr_id) ? HkEventType::$event_arr_id : $event_arr_id;
            $date = input('post.keyword_time/a', []);
            if ($work_area_id > 0) {
                //获取全部摄像头
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                $device_serial_where[] = ['device_serial', 'in', $device_serial];
            }
            //站点筛选
            if ($work_area_stand_id > 0) {
                $device_serial_where[] = ['work_area_stand_id', '=', $work_area_stand_id];
            }
            $hk_event_type = HkEventType::where(['id' => $event_arr_id])->field('id,remarks')->order("sort DESC")->cache(60)->select()->toArray();
            //获取全部使用摄像头
            $device_serial = HkDeviceSerial::where(['delete_time' => 0])
                ->where($device_serial_where)
                ->group('device_serial')
                ->column('device_serial', 'id');
            $where = [];
            if (!empty($channel_no)) {
                $where[] = ['channel_no', '=', $channel_no];
            }
            //时间筛选
            if (!empty($date)) {
                $timeWhere = timeWhere($date[0], $date[1]);
                $where[] = ['date_time', 'between', [$timeWhere[0], $timeWhere[1] + 86399]];
            }
            foreach ($hk_event_type as $key => $val) {
                $count = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => $val['remarks']])->where($where);
                if ($date_type == 1) $count->whereDay('create_time');//今天
                if ($date_type == 2) $count->whereDay('create_time', 'yesterday');//昨天
                $count = $count->cache(60)->count('*');
                $hk_event_type[$key]['count'] = $count;
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $hk_event_type);
    }


    /**
     * @Apidoc\Title("最新一次事件统计")
     * @Apidoc\Url("/applet/work_area.Info/consumerMsgFind")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("type",type="int", desc="1今日 2昨日 3历史")
     * @Apidoc\Param("msg_name",type="string", desc="事件检测类型 查看全部传空")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("date_time", type="string", desc="抓拍时间"),
     *    @Apidoc\Returned("device_serial_name", type="string", desc="摄像口名字"),
     *    @Apidoc\Returned("bname", type="string", desc="站点名字"),
     *    @Apidoc\Returned("cname", type="string", desc="工区名字"),
     *    @Apidoc\Returned("image_url", type="string", desc="网络图片"),
     *    @Apidoc\Returned("server_img_url", type="string", desc="本地图片"),
     * )
     */
    public function consumerMsgFind()
    {
        try {
            $work_area_id = input('post.work_area_id/d', 0);
            $type = input('post.type/d', 1);
            $msg_name = input('post.msg_name/s', '');
            $device_serial_where = [];
            if ($work_area_id > 0) {
                //获取全部摄像头
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                $device_serial_where[] = ['device_serial', 'in', $device_serial];
            }
            //获取全部使用摄像头
            $device_serial = HkDeviceSerial::where(['delete_time' => 0])->where($device_serial_where)->group('device_serial')->column('device_serial', 'id');
            if (!empty($msg_name)) $device_serial_where[] = ['msg_name', '=', $msg_name];
            //只获取下面数组事件
            $event_arr = BusinessService::$event_arr;
            $info = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_type' => $event_arr])
                ->where('image_url', 'not null')
                ->where($device_serial_where);
            //根据时间搜索
            switch ($type) {
                //当天
                case 1:
                    $info = $info->whereDay('date_time');
                    break;
                //昨天
                case 2:
                    $info = $info->whereDay('date_time', 'yesterday');
                    break;
            }

            $info = $info->field(['id', 'date_time', 'device_serial', 'channel_no', 'msg_name', 'image_url', 'server_img_url'])
                ->order('date_time DESC')
                ->find();
            if (!empty($info)) {
                $info = $info->toArray();
                $info['date_time'] = date("Y-m-d H:i", $info['date_time']);
                //查询摄像口名字
                $device_serial = HkDeviceSerial::alias("a")
                    ->join("work_area_stand b ", " b.id = a.work_area_stand_id", 'left')
                    ->join("work_area c ", " c.id = b.work_area_id", 'left')
                    ->where(['a.device_serial' => $info['device_serial'], 'a.channel_no' => $info['channel_no']])
                    ->field(['a.id', 'a.name', 'b.name bname', 'c.name cname'])
                    ->find();
                $info['device_serial_name'] = $device_serial->name ?? '';
                $info['bname'] = $device_serial->bname ?? '';
                $info['cname'] = $device_serial->cname ?? '';
                $info['server_img_url'] = get_file_url($info['server_img_url']);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $info);
    }


    /**
     * @Apidoc\Title("工区列表")
     * @Apidoc\Url("/applet/work_area.Info/workAreaList")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     *    @Apidoc\Returned("count", type="int", desc="次数")
     * )
     */
    public function workAreaList()
    {
        try {
            $where = [];
            //工区
            $work_area_id = input('post.work_area_id/d', 0);
            if ($work_area_id > 0) $where['id'] = $work_area_id;
            //工点
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            if ($work_area_stand_id > 0) {
                $work_area_id = WorkAreaStand::where(['id' => $work_area_stand_id])->value('work_area_id');
                $where['id'] = $work_area_id;
            }
            //只获取下面数组事件
            $event_arr_id = HkEventType::$event_arr_id;
            //获取报警事件
            $hk_event_type = HkEventType::where(['id' => $event_arr_id])->field('id,remarks')->cache(600)->select()->toArray();

            //获取工区
            $list = WorkArea::where($where)
                ->where('proj_line_id', '<>', 5)
                ->field(['id', 'name'])
                ->order("sort DESC")
                ->cache(600)->select()->toArray();
            foreach ($list as $key => $val) {
                $list[$key]['work_area_stand'] = [];
                //查询出工区下的所有工点、站点
                $work_area_stand = WorkAreaStand::where(['work_area_id' => $val['id']])->field(['id', 'name', 'addr', 'is_use'])->cache(1)->select()->toArray();
                if (!empty($work_area_stand)) {
                    //循环获取工点下报警事件统计
                    foreach ($work_area_stand as $kk => $vv) {
                        //获取全部摄像头
                        $device_serial = BusinessService::siteDeviceList($vv['id']);
                        foreach ($hk_event_type as $v) {
                            $count = HkConsumerMsgWeek::where(['device_serial' => $device_serial, 'msg_name' => $v['remarks']])->cache(600)->count('*');
                            $work_area_stand[$kk]['count'][] = [
                                'count' => $count,
                                'name' => $v['remarks'],
                            ];
                        }
                    }
                    $list[$key]['work_area_stand'] = $work_area_stand;
                }
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $list);
    }


    /**
     * @Apidoc\Title("站点列表")
     * @Apidoc\Url("/applet/work_area.Info/siteList")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     *    @Apidoc\Returned("count", type="int", desc="次数"),
     * )
     */
    public function siteList()
    {
        try {
            $where = [];
            $where[] = ['is_use', '=', 1];
            $work_area_id = input('post.work_area_id/d', 0);
            if ($work_area_id > 0) $where[] = ['work_area_id', '=', $work_area_id];
            //只获取下面数组事件
            $event_arr_id = HkEventType::$event_arr_id;
            //只获取下面数组事件
            $event_arr = BusinessService::$event_arr;
            $hk_event_type = HkEventType::where(['id' => $event_arr_id])->field('id,remarks')->select()->toArray();
            //站点列表
            $list = WorkAreaStand::where($where)->order('sort DESC')->field(['id', 'name', 'addr'])->select()->toArray();
            foreach ($list as $key => $val) {
                //获取全部摄像头
                $device_serial = BusinessService::siteDeviceList($val['id']);
                foreach ($hk_event_type as $k => $v) {
                    $hk_event_type[$k]['count'] = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => $v['remarks'], 'msg_type' => $event_arr])->count('*');
                }
                $list[$key]['hk_event_type'] = $hk_event_type;
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $list);
    }


    /**
     * @Apidoc\Title("设备列表")
     * @Apidoc\Url("/applet/work_area.Info/deviceList")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     *    @Apidoc\Returned("count", type="int", desc="次数"),
     * )
     */
    public function deviceList()
    {
        try {
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            $where = [];
            if ($work_area_stand_id > 0) $where[] = ['work_area_stand_id', '=', $work_area_stand_id];
            //$work_area_stand_id = WorkAreaStand::where($where)->column('id');
            $device_serial = HkDeviceSerial::where($where)
                ->cache(30)
                ->field(['id', 'name', 'channel_no', 'device_serial'])
                ->order('device_serial ASC')
                ->select()
                ->toArray();

        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $device_serial);
    }

    /**
     * @Apidoc\Title("报警消息列表")
     * @Apidoc\Url("/applet/work_area.Info/consumerMsgList")
     * @Apidoc\Param("type",type="int", desc="1今日 2昨日 3历史")
     * @Apidoc\Param("msg_name",type="string", desc="事件检测类型 查看全部传空")
     * @Apidoc\Param("page", type="int", desc="第几页默认第1页")
     * @Apidoc\Param("page_size", type="int", desc="每页几条默认10条")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("work_area_stand_id",type="int", desc="站点id 默认值传0")
     * @Apidoc\Param("device_serial",type="string", desc="设备号")
     * @Apidoc\Param("channel_no",type="string", desc="通道号")
     * @Apidoc\Param("event_arr_id",type="array", desc="事件数组id")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("date_time", type="string", desc="抓拍时间"),
     *    @Apidoc\Returned("name", type="string", desc="摄像口名字"),
     *    @Apidoc\Returned("bname", type="string", desc="站点名字"),
     *    @Apidoc\Returned("cname", type="string", desc="工区名字"),
     *    @Apidoc\Returned("image_url", type="string", desc="网络图片"),
     *    @Apidoc\Returned("server_img_url", type="string", desc="本地图片"),
     *    @Apidoc\Returned("channel_no", type="int", desc="通道号"),
     *    @Apidoc\Returned("type", type="string",desc="1海康 2流媒体"),
     *    @Apidoc\Returned("rtp_url", type="string",desc="流媒体地址"),
     *    @Apidoc\Returned("rtp_device_serial", type="string",desc="流媒体设备序列号"),
     *    @Apidoc\Returned("rtp_channel_no", type="string",desc="流媒体通道号")
     * )
     */
    public function consumerMsgList()
    {
        try {
            $where = [];
            $param = $this->request->param();
            $page_size = empty($param['page_size']) ? 10 : $param['page_size'];

            $work_area_id = input('post.work_area_id/d', 0);//工区ID
            $msg_name = input('post.msg_name/s', '');
            $channel_no = input('post.channel_no/s', '');

            if (!empty($msg_name)) $where[] = ['msg_name', '=', $msg_name];
            //工区筛选
            if ($work_area_id > 0 && empty($channel_no)) {
                $work_area_stand_ids = WorkAreaStand::where(['work_area_id' => $work_area_id])->column('id');
                $where[] = ['work_area_stand_id', 'in', $work_area_stand_ids];
            }
            //站点筛选
            $work_area_stand_id = input('post.work_area_stand_id/d', 0);
            if ($work_area_stand_id > 0 && empty($channel_no)) {
                $where[] = ['work_area_stand_id', '=', $work_area_stand_id];
            }
            $device_serial = input('post.device_serial/s', 0);

            //通道号查询记录
            if (!empty($device_serial) && !empty($channel_no)) {
                $where[] = ['device_serial', '=', $device_serial];
                $where[] = ['channel_no', '=', $channel_no];
            }

            //只获取下面数组事件
            $event_arr_id = input('post.event_arr_id/a', []);
            $event_where = [];
            if (!empty($event_arr_id)) {
                $event_where[] = ['id', 'in', $event_arr_id];
            } else {
                $event_where[] = ['id', 'in', HkEventType::$event_arr_id];
            }
            $hk_event_type = HkEventType::where($event_where)->cache(300)->column('remarks');
            $where[] = ['msg_name', 'in', $hk_event_type];
            //海康取流认证
            //$hk_account_token = HaikangService::ezvizAccountInfo();

            $list_ = HkConsumerMsgWeek::where($where)
                ->where('image_url', 'not null');

            $type = input('post.type/d', 1);
            //根据时间搜索
            switch ($type) {
                //当天
                case 1:
                    $list_->whereDay('date_time');
                    break;
                //昨天
                case 2:
                    $list_->whereDay('date_time', 'yesterday');
                    break;
            }
            $list_ = $list_->field(['id', 'msg_name', 'yj_data_id', 'channel_no', 'device_serial', 'image_url', 'server_img_url', 'date_time'])
                ->order("date_time DESC")
                ->paginate($page_size)
                ->toArray();
            $list = $list_ ['data'];
            foreach ($list as $key => $val) {
                $list[$key]['date_time'] = date("Y-m-d H:i", $val['date_time']);
                $list[$key]['server_img_url'] = get_file_url($val['server_img_url']);
                //查询摄像口名字
                $device_serial = HkDeviceSerial::alias("a")
                    ->join("work_area_stand b ", " b.id = a.work_area_stand_id", 'left')
                    ->join("work_area c ", " c.id = b.work_area_id", 'left')
                    ->where(['a.device_serial' => $val['device_serial'], 'a.channel_no' => $val['channel_no']])
                    ->field(['a.id', 'a.name', 'a.rtp_type type', 'a.rtp_url_whole', 'a.rtp_device_serial', 'a.rtp_channel_no', 'a.rtp_url', 'b.name bname', 'c.name cname'])
                    ->cache(60)
                    ->find();
                $list[$key]['name'] = $device_serial->name;
                $list[$key]['bname'] = $device_serial->bname;
                $list[$key]['cname'] = $device_serial->cname;
                $list[$key]['type'] = $device_serial->type;
                $list[$key]['rtp_url'] = $device_serial->rtp_url;
                $list[$key]['rtp_device_serial'] = $device_serial->rtp_device_serial;
                $list[$key]['rtp_channel_no'] = $device_serial->rtp_channel_no;
                $list[$key]['rtp_url_whole'] = $device_serial->rtp_url_whole;
                //红牌楼设备号
                if ($val['device_serial'] == 'AD5513816') {
                    $list[$key]['device_serial'] = 'AW1942779';
                    $list[$key]['hk_account_token']['token'] = 'ra.0uja6itzdfjqlw6a50vn4neoa7lhs19e-32hmv0govp-0cubx9t-dgsdfomfl';
                } else {
                    // $list[$key]['hk_account_token'] = $hk_account_token;
                }
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage() . $e->getLine() . $e->getFile());
        }
        return $this->ajax(1, "成功", [
            'list' => $list,
            'total' => $list_['total'],
            'page_size' => $page_size,
        ]);
    }


    /**
     * @Apidoc\Title("项目对比")
     * @Apidoc\Url("/applet/work_area.Info/projContrast")
     * @Apidoc\Param("work_area_id",type="int", desc="工区id 默认值传0")
     * @Apidoc\Param("date",type="array", desc="工时间筛选")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     *    @Apidoc\Returned("count", type="int", desc="次数"),
     * )
     */
    public function projContrast()
    {
        $work_area_id = input('post.work_area_id/d', 0);
        $keyword_time = input('post.keyword_time/a', []);
        $keyword_time = timeWhere($keyword_time[0], $keyword_time[1]);
        //查看整个工区对比
        if ($work_area_id == 0) {
            $axial = WorkArea::order("sort DESC")->where("proj_line_id <> 5")->field(['id', 'name', '1 as type', "abbr as simple"])->select()->toArray();
        } else {
            //查看工区下工点对比
            $axial = WorkAreaStand::where(['work_area_id' => $work_area_id])->order("sort DESC")->field(['id', 'name', '2 as type', "name as simple"])->cache(600)->select()->toArray();
        }
        //只获取下面数组事件
        $event_arr_id = input('post.event_arr_id/a', []);
        $event_where = [];
        if (!empty($event_arr_id)) {
            $event_where[] = ['id', 'in', $event_arr_id];
        } else {
            $event_where[] = ['id', 'in', HkEventType::$event_arr_id];
        }
        $hk_event_type = HkEventType::where($event_where)->cache(300)->column('remarks');

        foreach ($axial as $key => $val) {
            $hk_consumer_msg_where = [];
            //工区查询设备号
            if ($val['type'] == 1) {
                $hk_consumer_msg_where[] = ['work_area_stand_id', 'in', WorkAreaStand::where(['work_area_id' => $val['id']])->column('id')];
            } else {
                //工点查询设备号
                $hk_consumer_msg_where[] = ['work_area_stand_id', '=', $val['id']];
            }
            foreach ($hk_event_type as $k => $v) {
                $axial[$key]['event_type'][$k]['name'] = $v;
                $axial[$key]['event_type'][$k]['count'] = 0;
                if (!empty($hk_consumer_msg_where)) {
                    $axial[$key]['event_type'][$k]['count'] = HkConsumerMsg::where(['msg_name' => $v])
                        ->where($hk_consumer_msg_where)
                        ->whereTime('create_time', 'between', [$keyword_time[0], $keyword_time[1] + 86399])
                        ->cache(300)
                        ->count('*');
                }
            }
            unset($hk_consumer_msg_where);
        }
        return $this->ajax(1, '成功', $axial);
    }


    /**
     * @Apidoc\Title("报警消息统计导出")
     * @Apidoc\Url("/applet/work_area.Info/consumerMsgListExport")
     * @Apidoc\Param("work_area_id",type="int", desc="项目id、工区id")
     * @Apidoc\Param("keyword_time", type="array", desc="在岗日期 数组0开始 1结束")
     * @Apidoc\Param("event_arr_id",type="array", desc="报警类型数组id")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     * )
     */
    public function consumerMsgListExport()
    {
        try {
            $work_area_id = input('post.work_area_id/d', 0);
            $keyword_time = input('post.keyword_time/a', [date('Y-m-d'), date('Y-m-d')]);
            $event_arr_id = input('post.event_arr_id/a', [4, 13, 23]);
            //报警字段对应
            $report = ['安全帽未佩戴' => 'report1', '抽烟' => 'report2', '反光衣未穿戴' => 'report3', '打电话' => 'report4', '临边防护' => 'report5'];
            $hk_event_type = HkEventType::where([['id', 'in', $event_arr_id]])->cache(600)->column('remarks');
            $date = generateDateRangeArray($keyword_time[0], $keyword_time[1]);
            //全部工区
            if ($work_area_id == 0) {
                $axial = WorkArea::order("sort DESC")->field(['id', 'name'])->select()->toArray();
                $data['list'] = [];
                //循环工区
                foreach ($axial as $key => $val) {
                    //获取工区下所有的摄像头
                    $device_serial = BusinessService::areaDeviceList($val['id']);
                    //循环时间
                    foreach ($date as $kk => $vv) {
                        $data['list'][] = [
                            'create_time' => $vv,
                            'name' => $val['name'],
                            'id' => $val['id'],
                            'device_serial' => $device_serial,
                        ];
                    }
                }
                //循环报警状态获取
                foreach ($data['list'] as $key => $val) {
                    $data['list'][$key]['sum'] = 0;
                    foreach ($hk_event_type as $v) {
                        $report_field = $report[$v];
                        $data['list'][$key][$report_field] = 0;
                        if (!empty($val['device_serial'])) {
                            $count = HkConsumerMsg::where(['device_serial' => $val['device_serial'], 'msg_name' => $v])
                                ->whereDay('create_time', $val['create_time'])
                                ->cache(600)
                                ->count('*');
                            $data['list'][$key][$report_field] = $count;
                            $data['list'][$key]['sum'] += $count;
                        }
                    }
                }
                //点击导出
                $arytitle = [
                    array('create_time', 'A'),
                    array('name', 'B'),
                    array('sum', 'C'),
                    array('report1', 'D'),
                    array('report2', 'E'),
                    array('report3', 'F'),
                    array('report4', 'G'),
                    array('report5', 'H'),
                ];
                $res = BusinessService::workAreaExport($arytitle, $data, 2);
            } else {
                $timeWhere = timeWhere($keyword_time[0], $keyword_time[1]);
                //获取工区下所有的设备号
                $device_serial = BusinessService::areaDeviceList($work_area_id);
                //指定工区
                $name = WorkArea::where(['id' => $work_area_id])->value('name');
                $data['a1'] = '中铁成都轨道交通AI视频集成管理系统平台数据统计表-' . $name;
                $data['b3'] = $keyword_time[0];
                $data['c3'] = $keyword_time[1];
                $data['d3'] = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => '安全帽未佩戴'])->whereTime('create_time', 'between', [$timeWhere[0], $timeWhere[1] + 86399])->cache(600)->count('*');
                $data['e3'] = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => '抽烟'])->whereTime('create_time', 'between', [$timeWhere[0], $timeWhere[1] + 86399])->cache(600)->count('*');
                $data['f3'] = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => '反光衣未穿戴'])->whereTime('create_time', 'between', [$timeWhere[0], $timeWhere[1] + 86399])->cache(600)->count('*');
                $data['g3'] = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => '打电话'])->whereTime('create_time', 'between', $keyword_time)->cache(600)->count('*');
                $data['h3'] = HkConsumerMsg::where(['device_serial' => $device_serial, 'msg_name' => '临边防护'])->whereTime('create_time', 'between', [$timeWhere[0], $timeWhere[1] + 86399])->cache(600)->count('*');

                $data['list'] = HkConsumerMsg::alias('a')
                    ->join("hk_device_serial b", " b.device_serial = a.device_serial", 'left')
                    ->where(['a.device_serial' => $device_serial, 'a.msg_name' => $hk_event_type])
                    ->whereTime('a.create_time', 'between', [$timeWhere[0], $timeWhere[1] + 86399])
                    ->field([
                        'a.id', 'a.msg_name', 'a.image_url', 'a.create_time', 'b.name'
                    ])
                    ->cache(600)
                    ->order("a.id DESC")
                    ->group("a.id")
                    ->select()
                    ->toArray();
                //点击导出
                $arytitle = [
                    array('create_time', 'A'),
                    array('name', 'B'),
                    array('msg_name', 'C'),
                    array('image_url', 'D')
                ];
                $res = BusinessService::workAreaExport($arytitle, $data);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $res);
    }


    /**
     * @Apidoc\Title("报警消息统计导出")
     * @Apidoc\Url("/applet/work_area.Info/warningStatistics")
     * @Apidoc\Param("name",type="string", desc="站点名称")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     * )
     */
    public function warningStatistics()
    {
        try {
            $param = $this->request->param();

            $work_area_stand = WorkAreaStand::where(['name' => $param['name']])->find();
            //获取站点所有设备号
            $device_serial = BusinessService::siteDeviceList($work_area_stand->id);
            //获取预警类型
            $hk_event_type = HkEventType::where('id', 'in', HkEventType::$event_arr_id)
                ->cache(300)
                ->column('remarks');
            $date_list = generateDateRangeArray(date('Y-m-d', strtotime('-6 days')), date('Y-m-d'));
            $list = [];
            foreach ($date_list as $key => $val) {
                $list[$key]['date'] = $val;
                foreach ($hk_event_type as $v) {
                    $count = HkConsumerMsg::where([
                        'device_serial' => $device_serial,
                        'msg_type' => $v
                    ])->whereWeek('create_time', $val)->cache(600)->count('*');
                    $list[$key]['hk_event_type'][] = [
                        'type' => $v,
                        'count' => $count,
                    ];
                }
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $list);
    }

    /**
     * @Apidoc\Title("实时预警")
     * @Apidoc\Url("/applet/work_area.Info/earlyWarning")
     * @Apidoc\Param("name",type="string", desc="站点名称")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("remarks", type="string", desc="报警事件"),
     * )
     */
    public function earlyWarning()
    {
        try {
            $param = $this->request->param();
            Validate([
                'name|站点名称' => 'require',
            ])->check($param);
            $work_area_stand = WorkAreaStand::where(['name' => $param['name']])->find();
            //获取站点所有设备号
            $device_serial = BusinessService::siteDeviceList($work_area_stand->id);

            $list = HkConsumerMsg::where([
                'device_serial' => $device_serial
            ])
                ->field(['id', 'msg_name', 'server_img_url', 'channel_no', 'create_time', 'device_serial'])
                ->limit(5)
                ->order('create_time DESC')
                ->select()
                ->toArray();
            foreach ($list as $key => $val) {
                $device_serial = HkDeviceSerial::where([
                    'device_serial' => $val['device_serial'],
                    'channel_no' => $val['channel_no']
                ])
                    ->cache(600)
                    ->field(['id', 'name', 'remarks'])
                    ->find();
                $list[$key]['device_serial'] = $device_serial;
            }

        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "成功", $list);
    }

}